<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog" width="70%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             class="full-form"
             label-width="100px"
             status-icon>

      <el-form-item label="模型名称：" prop="name">
        <el-input v-model="formData.name" :readonly="readonly" maxlength="64" placeholder="请输入模型名称" show-word-limit/>
      </el-form-item>

      <el-form-item label="模型简介：" prop="profile">
        <el-input v-model="formData.profile" :readonly="readonly" maxlength="128" placeholder="请输入模型简介" show-word-limit/>
      </el-form-item>

      <el-form-item label="模型状态：" prop="status">
        <DictSelect v-if="!readonly" v-model="formData.status"
                    :clearable="false"
                    :show-default="false"
                    dict-type="goods_model_status"
                    placeholder="请选择模型状态"
                    style="width: 50%;margin-right: 6px"/>
        <DictTag v-model="formData.status" :circle="false" dict-type="goods_model_status"/>
      </el-form-item>
    </el-form>

    <div class="spec-list">
      <!-- 添加 -->
      <div v-if="!readonly" style="margin-bottom: 10px">
        <el-button icon="circle-plus" plain type="danger" @click="handleAddSpec">添加规格</el-button>
      </div>

      <!-- 模型规格 -->
      <el-table :data="specList" border fit highlight-current-row style="width: 100%">
        <el-table-column align="center" label="规格名称" prop="name" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.name" :readonly="readonly" clearable placeholder="规格名称"></el-input>
          </template>
        </el-table-column>

        <el-table-column align="center" label="规格状态" prop="status" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" active-text="上架" inactive-text="下架" inline-prompt/>
          </template>
        </el-table-column>

        <el-table-column align="center" label="排序" prop="order_num" width="130">
          <template #default="scope">
            <el-input-number v-model="scope.row.order_num" :disabled="readonly || scope.row.id > 0" :max="1000" :min="0" controls-position="right"/>
          </template>
        </el-table-column>

        <el-table-column align="left" header-align="center" label="规格值" min-width="200" prop="specItems">
          <template #default="scope">
            <DynamicTags :disabled="readonly" :dynamic-tags="scope.row.spec_items"/>
          </template>
        </el-table-column>

        <el-table-column v-if="!readonly" align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="100px">
          <template #default="scope">
            <el-button v-if="scope.row.id === 0" icon="delete" size="small" type="danger" @click="handleRemoveSpec(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['shop:goods_model:create', 'shop:goods_model:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { DictSelect } from '@/components/dict-select';
import { defGoodsModel, GoodsModelSpec, GoodsModelSpecItem, modelInfo, modelSaveOrUpdate } from '@/api/api-shop.ts';
import { DynamicTags } from '@/components/dynamic-tags';
import { DictTag } from '@/components/dict-tag';

defineOptions({name: 'goods-model-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

// 表单数据
const formData = ref({...defGoodsModel});
const specList = ref<GoodsModelSpec[]>([]);
const maxSpecSize = ref(30);

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{required: true, message: '模型名称不能为空', trigger: 'change'}],
  status: [{required: true, message: '模型状态不能为空', trigger: 'change'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || formData.value.id <= 0;
});

/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '商品模型';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();

  // 加载数据
  if (id) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {data} = await modelInfo(id)
      formData.value = data;
      specList.value = data.spec_list || [];
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open})

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })

    // 数据组装
    let params = Object.assign({}, formData.value)
    let newSpecList: GoodsModelSpec[] = []
    specList.value.forEach(spec => {
      let newSpec = Object.assign({}, spec)
      let specItems: GoodsModelSpecItem[] = []
      newSpec.spec_items.map((it, index) => specItems.push(<GoodsModelSpecItem>{id: it.id, item: it.item, order_num: index}))
      newSpec.spec_items = specItems
      newSpecList.push(newSpec)
    })
    params.spec_list = newSpecList;

    // 提交数据
    modelSaveOrUpdate(params, isCreate.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defGoodsModel};
  formData.value.spec_list = [];
  specList.value = [];
  // 重置界面表单数据
  formRef.value?.resetFields();
};

/** 添加新规格 */
const handleAddSpec = () => {
  if (specList.value.length >= maxSpecSize.value) {
    ElMessage.error(`规格最多可添加${maxSpecSize.value}个`);
    return
  }
  let orderNum = specList.value.length > 0 ? Math.max(...specList.value.map(item => item.order_num)) + 1 : 1;
  let newSpec: GoodsModelSpec = {id: 0, model_id: 0, name: '', order_num: orderNum, status: 1, spec_items: [], select_ids: []};
  specList.value.push(newSpec);
};

/** 删除临时添加的规格 */
const handleRemoveSpec = (item: GoodsModelSpec) => {
  if (item.id > 0) return
  specList.value.splice(specList.value.indexOf(item), 1)
};

</script>

<style lang="scss" scoped>
.form-dialog {

}

.spec-list {
  .el-input-number {
    width: 100%;
  }

  :deep(.el-table__cell) {
    //vertical-align: top;
  }
}


</style>
